<?php
/**
 * User: Jerry
 * Date: 2017/7/1
 * Time: 14:19
 */

namespace SDXApi\Service;


use SDXApi\Listeners\LocationLinkSourceListener;
use SDXApi\Model\NavTestUserModel;
use SDXApi\Model\TouchNavModel;

/**
 * Class NavService
 * @author Jerry
 * @package SDXApi\Service
 */
class NavService
{
    /**
     * @var TouchNavModel
     */
    protected  $navModel;

    /**
     * @var
     */
    protected $error;

    /**
     * @var LocationLinkSourceListener
     */
    protected $linkListener;

    protected $testUserModel;

    /**
     * @var
     */
    protected $navData;

    /**
     * NavService constructor.
     */
    public function __construct()
    {
        $this->navModel = new TouchNavModel();
        $this->linkListener = new LocationLinkSourceListener();
        $this->testUserModel = new NavTestUserModel();
    }

    /**
     * @author Jerry
     * @param int $uid
     * @return $this
     */
    public function getNav($uid = 0)
    {

        $result = $this->testUserModel->isTestByUserId($uid);

        $isTest = $result ? true : false;

        $navList = $this->navModel->get_touch_nav_list($isTest);

        if (empty($navList)) {
            $this->error = '暂无数据';
            return $this;
        }

        $this->navData = $this->handleLink($navList);

        return $this;
    }

    /**
     * @author Jerry
     * @param array $data
     * @return array|bool
     */
    protected function handleLink($data = array())
    {
        if (empty($data)) {
            $this->error = '获取数据出错';
            return false;
        }

        foreach ($data as $key => $value) {

            if (! empty($value['url'])) {
                $linkData = $this->linkListener->onCallLink($value['url']);

                if (! empty($linkData)) {
                    $data[$key]['link_data'] = $linkData;
                }
            }
        }

        return $data;
    }

    /**
     * @author Jerry
     * @return mixed
     */
    public function get()
    {
        return $this->navData;
    }
}